package com.nononsenseapps.feeder.worker

import android.content.Context
import androidx.work.*
import com.nononsenseapps.feeder.db.room.AppDatabase
import com.nononsenseapps.feeder.db.entity.Feed
import com.nononsenseapps.feeder.net.HtmlPageLoader
import com.nononsenseapps.feeder.processor.ProcessorManager
import timber.log.Timber

class FullPageLoader (val context: Context, workerParams: WorkerParameters) : CoroutineWorker(context, workerParams) {
    override suspend fun doWork(): Result {
        var success = false
        Timber.d("FullPageLoader working....")
        if (isOkToSyncAutomatically(context)) {
            syncFeedItemFullPage(context)
            success=true
        }
        return when (success) {
            true -> Result.success()
            false -> Result.failure()
        }
    }
}

suspend fun syncFeedItemFullPage(context: Context){
    Timber.d("syncFeedItemFullPage working....")
    val db = AppDatabase.getInstance(context)
    val feedItemDao = db.feedItemDao()
    val feedDao = db.feedDao()
    val feedCache = mutableMapOf<Long, Feed>()
    feedItemDao.loadFeedItemsWithFullTextSync().forEach { id ->
        feedItemDao.loadFeedItem(id)?.let{item->
            item.link?.let{url->
                if(item.fullTextSync) {
                    loadHtmlPage(url)?.let { description ->
                            item.description = description
                            item.fullTextSync = false
                            feedItemDao.updateFeedItem(item)
                            item.feedId?.let {
                                if (feedCache[it] == null) {
                                    feedCache[it] = feedDao.loadFeed(it)!!
                                }
                            ProcessorManager.default.dispatch(feedCache[it]!!, item, context)
                            }
                    }
                }
            }
        }
    }
}

suspend fun loadHtmlPage(url:String):String? = try{
    HtmlPageLoader.loadHtmlPage(url)
}catch (t:Exception){
    Timber.d(t)
    null
}

fun requestFeedFullPageSync(context: Context){
    val workRequest = OneTimeWorkRequestBuilder<FullPageLoader>()

    WorkManager.getInstance(context).enqueueUniqueWork("FullPageLoader",
        ExistingWorkPolicy.KEEP,workRequest.build())
}